package in.co.codedoc.events.tests;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import in.co.codedoc.event.AsynchronousEventRegistry;
import in.co.codedoc.event.EventHandler;
import in.co.codedoc.event.SynchronousEventRegistry;
import in.co.codedoc.events.tests.SyncEventTests.TestEvent0;
import in.co.codedoc.events.tests.SyncEventTests.TestEvent1;
import in.co.codedoc.events.tests.SyncEventTests.TestEvent2;
import in.co.codedoc.events.tests.SyncEventTests.TestEventHandler;
import in.co.codedoc.ioc.IOCContainer;
import in.co.codedoc.sql.DBInteractions;
import in.co.codedoc.tests.JUNitTestBase;

public class AsynchronousEventProcessorTests
	extends JUNitTestBase
{
	public static class AEventHandler
	{
		@EventHandler
		public void Foo1(AEvent0 ev0)
		{
			total0 += ev0.GetP00();
		}
		
		@EventHandler
		public void Foo1(AEvent1 ev1)
		{
			total1 += ev1.GetP11();
		}
		
		public int total0 = 0;
		public int total1 = 0;
	}
	
	@Test
	public void TestBasicOps() 
		throws InterruptedException
	{
		AsynchronousEventRegistry aer
			= IOCContainer.Lookup(AsynchronousEventRegistry.class);
	
		AEventHandler teh = new AEventHandler();
		aer.Register(AEvent0.class, teh);
		aer.Register(AEvent1.class, teh);
		
		DBInteractions.StartNewTransaction();
		try
		{
			SynchronousEventRegistry ser
				= IOCContainer.Lookup(SynchronousEventRegistry.class);
			ser.Dispatch(new AEvent0((short)1));
			ser.Dispatch(new AEvent1((short)4));
			ser.Dispatch(new AEvent0((short)16));
			ser.Dispatch(new AEvent1((short)64));
			DBInteractions.CommitTransaction();
		}
		catch(Throwable th)
		{
			DBInteractions.RollbackTransaction();
			
			throw new RuntimeException(th);
		}
		Thread.sleep(10000);
		
		assertEquals(17,teh.total0);
		assertEquals(68,teh.total1);
	}
}
